package com.tvein.sanguo.view
{
	//flash
	import flash.net.LocalConnection;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.events.StatusEvent;
	//pureMVC
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.utilities.fabrication.components.FlashApplication;
	import org.puremvc.as3.multicore.utilities.fabrication.patterns.mediator.FlashMediator;
	//custom
	import com.tvein.sanguo.common.CommonConstants;
	import com.tvein.SanGuo;
	import com.tvein.sanguo.model.ServerProxy;
	import com.tvein.sanguo.controller.Game.SystemConsole;
	import com.tvein.sanguo.controller.Game.GameConsole;
	import com.tvein.sanguo.controller.FileLoader.FileDown;
	import com.tvein.sanguo.controller.FileLoader.FileGet;
	import com.tvein.sanguo.controller.FileLoader.FileLoad;
	import com.tvein.sanguo.controller.FileLoader.preLoad;
//
	public class SystemMediator extends FlashMediator
	{
		public static const NAME:String = 'SystemMediator';
		
		public function SystemMediator(viewComponent:Object)
		{
			super(NAME, viewComponent);
		}
		
		public function get system():SanGuo
		{
			return viewComponent as SanGuo;
		}
		
		//Custom
		private var serverData:ServerProxy;
		private var conn:Boolean = false;
		private var sanguoConnection:LocalConnection;
		
		override public function onRegister() : void
        {
			serverData = facade.retrieveProxy(ServerProxy.NAME) as ServerProxy;
			
			try
			{
				var url:String = system.loaderInfo.url;
				
				if (url.indexOf("|") < 0)
				{
					//web mode
					CommonConstants.GAME_SERVER = url.substring(0, url.toLowerCase().indexOf("/sanguo/sanguo.swf"));
				}
				else
				{
					//local mode
					CommonConstants.GAME_SERVER = "http://127.0.0.1";
				}
			}
			catch  (err:Error)
			{
				//default mode
			}
			
			//LSO
			var checkTimer:Timer = new Timer(100);
			checkTimer.addEventListener(TimerEvent.TIMER, openConnection);
			checkTimer.start();
			
			//get server xml
			var loader:URLLoader = new URLLoader();
			loader.load(new URLRequest(CommonConstants.GAME_SERVER + "/server.xml?tmp=" + Math.random()));
			loader.addEventListener(Event.COMPLETE, _serverLoad);
			
			//System Command
			/*  -C console  */
			facade.registerCommand(CommonConstants.SYSTEM_CONSOLE, SystemConsole);
			facade.registerCommand(CommonConstants.GAME_CONSOLE, GameConsole);
			
			//FileLoader Command
			/*  -D filedown  */
			facade.registerCommand(CommonConstants.FILELOADER_FILEDOWN, FileDown);
			/*  -F fileget  */
			facade.registerCommand(CommonConstants.FILELOADER_FILEGET, FileGet);
			/*  -L fileload  */
			facade.registerCommand(CommonConstants.FILELOADER_FILELOAD, FileLoad);
			/*  -P preLoad  */
			facade.registerCommand(CommonConstants.FILELOADER_PRELOAD, preLoad);
        }
		
		private function openConnection(evt:TimerEvent):void
		{
			try
			{
				sanguoConnection = new LocalConnection();
				sanguoConnection.allowDomain(sanguoConnection.domain);
				sanguoConnection.connect(CommonConstants.GAME_CHANNEL);
				
				conn = true;
			}
			catch (error:ArgumentError)
			{
				conn = false;

				sanguoConnection.send(CommonConstants.GAME_CHANNEL, "console", ["close"]);
				sanguoConnection = null;
			}
			
			if (conn)
			{
				sanguoConnection.client = this;
				sanguoConnection.addEventListener(StatusEvent.STATUS, _onConnStatus);
				sanguoConnection.send(CommonConstants.SYSTEM_CHANNEL, "console", ["/system -T", CommonConstants.GAME_CHANNEL]);
				
				evt.target.stop();
				evt.target.removeEventListener(TimerEvent.TIMER, openConnection);
			}
		}
		
		override public function listNotificationInterests() : Array
		{
			var interests:Array = super.listNotificationInterests();
			interests.push(CommonConstants.SYSTEM);
			interests.push(CommonConstants.FILELOADER);
			return interests;
		}
		
		override public function handleNotification(notification:INotification) : void
		{
			var params:Array = notification.getBody()[0].split(" ");
			
			switch(notification.getName())
			{
				case CommonConstants.SYSTEM:
					switch(params[1])
					{
						case "-C":
							sendNotification(CommonConstants.SYSTEM_CONSOLE, notification.getBody()[1]);
							break;
					}
					break;
				case CommonConstants.FILELOADER:
					switch(params[1])
					{
						case "-D":
							sendNotification(CommonConstants.FILELOADER_FILEDOWN, notification.getBody()[1]);
							break;
						case "-F":
							sendNotification(CommonConstants.FILELOADER_FILEGET, notification.getBody()[1]);
							break;
						case "-P":
							sendNotification(CommonConstants.FILELOADER_PRELOAD, notification.getBody()[1]);
							break;
						case "-L":
							sendNotification(CommonConstants.FILELOADER_FILELOAD, notification.getBody()[1]);
							break;
					}
					break;
			}
			
			try
			{
				new LocalConnection().connect("Tvein");
				new LocalConnection().connect("Tvein");
			}
			catch (error : Error)
			{
			
			}
		}
		
		public function console(command:Array) : void
		{
			var params:Array = command[0].split(" ");
			
			switch(params[0])
			{
				case "close":
					sanguoConnection.close();
				case "/system":
					sendNotification(CommonConstants.SYSTEM, command);
					break;
				case "/fileloader":
					sendNotification(CommonConstants.FILELOADER, command);
					break;
			}
		}
		
		private function _onConnStatus(evt:StatusEvent):void
		{
			trace("connect " + evt.level);
			
			switch (evt.level)
			{
				case "status":
					serverData.p2pStatus = true;
					break;
				case "error":
					serverData.p2pStatus = false;
					break;
			}
		}
		
		private function _serverLoad(evt:Event):void
		{
			evt.target.removeEventListener(Event.COMPLETE, _serverLoad);
			serverData.serverXML = new XML(evt.target.data);
			
			sendNotification(CommonConstants.FILELOADER, ["/fileloader -P", "/SanGuo/preload.xml"]);
		}
    }
}